# -- coding: utf-8 --


class FileParser:   # 文件解析器

    @classmethod
    def read_json(cls, path):
        import json5
        with open(path, encoding='utf8') as file:
            contents = json5.load(file)
        return contents

    @classmethod
    def read_txt(cls, path, symbol):
        with open(path, encoding='utf8') as file:
            contents = file.readlines()
        result = []
        for item in contents:
            temp = item.strip()
            if not temp.startswith(symbol) and temp!='':
                if symbol in temp:
                    rl = temp.split(symbol)[0].strip()
                    result.append(rl)
                else:
                    result.append(temp)
        return result



class DBParser:    # 数据库解析器
    @classmethod
    def get_conn(cls, dbname):   # 先检查base.json文件中的键
        import pymysql
        db_info = FileParser.read_json('../base.json')
        return pymysql.connect(**db_info[dbname])

    @classmethod
    def update(cls, sql):
        conn = cls.get_conn('app_db')
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()

    @classmethod
    def query(cls, sql):
        conn = cls.get_conn('app_db')
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result


class UI:
    driver = None

    @classmethod
    def get_driver(cls, browser):
        from selenium import webdriver
        # 判断driver是否为空，为空证明是第一次打开浏览器，这时候需要实例化对象；如果不为空，则直接返回即可，不需要重新实例化
        if cls.driver is None:
            if hasattr(webdriver, browser):
                cls.driver = getattr(webdriver, browser)()
            else:
                cls.driver = webdriver.Firefox()
            cls.driver.implicitly_wait(5)
            cls.driver.maximize_window()
        return cls.driver

    @classmethod
    def get(cls, url):
        cls.driver.get(url)

    @classmethod
    def close(cls):
        cls.driver.quit()
        cls.driver = None

    @classmethod
    def refresh(cls):
        """
        页面刷新
        :return:
        """
        cls.driver.refresh()

    @classmethod
    def get_element(cls, locator):  # locator = {'by':'ID','what':'xxx'}
        """
        根据定位方式来查找元素对象，如果找不到返回None
        :param locator:
        :return:
        """
        by = locator['by']
        what = locator['what']
        try:

            from selenium.webdriver.common.by import By
            return cls.driver.find_element(getattr(By, by), what)
        except Exception as e:  # 没有找到，返回异常转回None
            return None

    @classmethod
    def input(cls, locator, value): # locator = ({'by':'ID','what':'xxx'},'woniu123')
        """
        向文本框元素输入内容
        :param locator: 定位方式
        :param value: 要输入的值
        :return: None
        """
        element = cls.get_element(locator)
        element.click()
        element.clear()
        element.send_keys(value)

    @classmethod
    def click(cls, locator): # locator = {'by':'ID','what':'xxx'}
        """
        点击某个元素
        :param locator:元素定位方式
        :return: None
        """
        element = cls.get_element(locator)
        element.click()

    @classmethod
    def select_option(cls,locator): # locator = {'by':'ID','what':'xxx'}
        """
        随机选择下拉数据某一项但不包括首行
        :param locator:
        :return:
        """
        element = cls.get_element(locator)
        from selenium.webdriver.support.select import Select
        size = len(Select(element).options)
        import random
        random_index = random.randint(1, size - 1)
        Select(element).select_by_index(random_index)

    @classmethod
    def exists(cls, locator):
        """
        判断某个元素是否存在，如果存在则返回True，否则返回False
        :param locator:元素定位器
        :return:boolean类型
        """
        if cls.get_element(locator) is None:
            return False
        else:
            return True


class Asserts:

    @classmethod
    def assert_equal(cls, expect, actual):
        if expect == actual:
            print('断言成功')
        else:
            print('断言失败')

    @classmethod
    def assert_contain(cls):
        pass

    @classmethod
    def assert_not_equal(cls):
        pass


if __name__ == '__main__':

    print(DBParser.get_conn('app_db'))